package product;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.Vector;

import javax.swing.JButton;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableRowSorter;

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

public class CodeUpdate extends JInternalFrame {
	Map<String, ProductData> hm = new HashMap<String, ProductData>();
	boolean mdf;
	int row;

	ProductData pd;
	Vector<String> colNam;	
	String[] rows = {"Code", "Name", "Cost", "Date"};
	DefaultTableModel dtm = new DefaultTableModel(null, rows);
	Vector<String> RowData;
	SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

	private JTextField pcInput;
	private JButton btnSearch;
	private JScrollPane scrollPane;
	private JTable table;
	private JLabel label;
	private JLabel label_1;
	private JLabel label_2;
	private JTextField pcInput2;
	private JTextField pnInput;
	private JTextField cosInput;
	private JButton btnMod;
	private JButton btnDel;
	private JButton btnClr;
	private JButton btnSearchAll;

	public CodeUpdate() {
		super("CodeUpdate",true,true,false,false);		

		setBounds(100, 100, 354, 384);
		getContentPane().setLayout(null);
		getContentPane().add(getPcInput());
		getContentPane().add(getBtnSearch());
		getContentPane().add(getScrollPane());
		getContentPane().add(getLabel());
		getContentPane().add(getLabel_1());
		getContentPane().add(getLabel_2());
		getContentPane().add(getPcInput2());
		getContentPane().add(getPnInput());
		getContentPane().add(getCosInput());
		getContentPane().add(getBtnMod());
		getContentPane().add(getBtnDel());
		getContentPane().add(getBtnClr());
		getContentPane().add(getBtnSearchAll());

		table.setRowSorter(new TableRowSorter(dtm));
		setCoulmnSize(table);

	}
	public void setD(Map<String, ProductData> map, boolean a){
		this.hm = map;
		this.mdf=a;
	}
	public void setCoulmnSize(JTable t){

		t.getTableHeader().setReorderingAllowed(false);      
		//테이블 컬럼의 이동을 방지한다. 이거 안쓰면 마우스로 드로그 앤 드롭으로 엉망진창이 될수 있다.

		t.getColumnModel().getColumn(0).setPreferredWidth(30);
		t.getColumnModel().getColumn(0).setResizable(false);
		t.getColumnModel().getColumn(1).setPreferredWidth(30);
		t.getColumnModel().getColumn(2).setPreferredWidth(30);		
		//t.getColumnModel().getColumn(5).setPreferredWidth(80);
		
	}
	private JTextField getPcInput() {
		if (pcInput == null) {
			pcInput = new JTextField();
			pcInput.setBounds(12, 10, 88, 21);
			pcInput.setColumns(10);
		}
		return pcInput;
	}
	private JButton getBtnSearch() {
		if (btnSearch == null) {
			btnSearch = new JButton("조회");
			btnSearch.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) { 
					if(pcInput.getText().equals("")){ // 조회 란이 공백일때,
						JOptionPane.showMessageDialog(null, "해당 정보가 존재하지 않습니다."); 
						return;
					}						
					try{
						String s = pcInput.getText();				
						Set<String> st = hm.keySet();	
						Iterator<String> it = st.iterator();
						
						int temp = dtm.getRowCount(); // 테이블에 데이터가 추가되기 전후의 행 크기를 저장해서 데이터가 없을때 메세지 출력을 하기위한 변수.
						while(it.hasNext()){
							pd = hm.get(it.next());
							if(pd.getpCode().contains(s) || pd.getpName().contains(s)){	// 제품 코드, 제품 명, 제품 단가 중 하나만 만족하면 검색.							

								RowData = new Vector<String>();
								RowData.add(pd.getpCode());
								RowData.add(pd.getpName());
								RowData.add(String.valueOf(pd.getCost()));
								RowData.add(sd.format(pd.getNal()));
								dtm.addRow(RowData);																							
							}
						}
												
						
						if(temp == dtm.getRowCount()){ // 조회 전 후의 테이블 행의 수가 같을 때 데이터가 추가 되지 않았으므로 정보가 없음 메세지 출력.
							JOptionPane.showMessageDialog(null, "해당 정보가 존재하지 않습니다.");
							return;
						}
						btnMod.setEnabled(true); // 데이터가 조회 되었으므로 삭제 수정 버튼 활성화.
						btnDel.setEnabled(true);

					}catch(NullPointerException ex){
						JOptionPane.showMessageDialog(null, "해당 정보가 존재하지 않습니다.");
					}

				}
			});
			btnSearch.setBounds(112, 9, 106, 23);
		}
		return btnSearch;
	}
	private JScrollPane getScrollPane() {
		if (scrollPane == null) {
			scrollPane = new JScrollPane();
			scrollPane.setBounds(12, 41, 315, 220);
			scrollPane.setViewportView(getTable());
		}
		return scrollPane;
	}
	private JTable getTable() {
		if (table == null) {
			table = new JTable(dtm);
			table.addMouseListener(new MouseAdapter() {
				@Override
				public void mousePressed(MouseEvent e) {
					int a = table.getSelectedRow();
					row=a;
					pcInput2.setText(String.valueOf(dtm.getValueAt(a, 0)));
					pnInput.setText(String.valueOf(dtm.getValueAt(a, 1)));
					cosInput.setText(String.valueOf(dtm.getValueAt(a, 2)));
				}
			});
		}
		return table;
	}
	private JLabel getLabel() {
		if (label == null) {
			label = new JLabel("제품코드");
			label.setHorizontalAlignment(SwingConstants.RIGHT);
			label.setBounds(12, 271, 57, 15);
		}
		return label;
	}
	private JLabel getLabel_1() {
		if (label_1 == null) {
			label_1 = new JLabel("제품명");
			label_1.setHorizontalAlignment(SwingConstants.RIGHT);
			label_1.setBounds(12, 296, 57, 15);
		}
		return label_1;
	}
	private JLabel getLabel_2() {
		if (label_2 == null) {
			label_2 = new JLabel("단가");
			label_2.setHorizontalAlignment(SwingConstants.RIGHT);
			label_2.setBounds(12, 321, 57, 15);
		}
		return label_2;
	}
	private JTextField getPcInput2() {
		if (pcInput2 == null) {
			pcInput2 = new JTextField();
			pcInput2.setEditable(false);
			pcInput2.setBounds(81, 268, 116, 21);
			pcInput2.setColumns(10);
		}
		return pcInput2;
	}
	private JTextField getPnInput() {
		if (pnInput == null) {
			pnInput = new JTextField();
			pnInput.setColumns(10);
			pnInput.setBounds(81, 293, 116, 21);
		}
		return pnInput;
	}
	private JTextField getCosInput() {
		if (cosInput == null) {
			cosInput = new JTextField();
			cosInput.setColumns(10);
			cosInput.setBounds(81, 318, 116, 21);
		}
		return cosInput;
	}
	private JButton getBtnMod() {
		if (btnMod == null) {
			btnMod = new JButton("수정");
			btnMod.setEnabled(false);
			btnMod.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					try{
						if(cosInput.getText().trim().equals("")){
							JOptionPane.showMessageDialog(null, "수정할 데이터를 선택해주세요.");
							return;
						}else{
							Date temp = hm.get(pcInput2.getText()).nal; // 생산날짜 초기화 방지용 temp
							ProductData pd = new ProductData(pcInput2.getText(), pnInput.getText(), Integer.parseInt(cosInput.getText()),temp);
							hm.put(pcInput2.getText(), pd);
							JOptionPane.showMessageDialog(null, "데이터가 수정되었습니다");
							pcInput.setText("");
							pnInput.setText("");
							cosInput.setText("");
							pcInput2.setText("");
							for (int i=dtm.getRowCount()-1; i>-1; i--) {
								dtm.removeRow(i);
							}
							mdf=true; // 수정여부
							pcInput.requestFocus();
							btnSearch.setEnabled(true);
						}
					}catch(NumberFormatException nfe){
						JOptionPane.showMessageDialog(null, "단가는 숫자만 입력해주세요.");
					}
					btnMod.setEnabled(false);
					btnDel.setEnabled(false);
				}
			});
			btnMod.setBounds(209, 267, 118, 23);
		}
		return btnMod;
	}
	private JButton getBtnDel() {
		if (btnDel == null) {
			btnDel = new JButton("삭제");
			btnDel.setEnabled(false);
			btnDel.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					if(pcInput2.getText().trim().equals("") || pnInput.getText().trim().equals("") || cosInput.getText().trim().equals("")){
						JOptionPane.showMessageDialog(null, "삭제하실 데이터를 선택해주세요.");
						return;
					}

					int yn = JOptionPane.showConfirmDialog(null, "정말로 삭제하시겠습니까?");
					if(yn == JOptionPane.YES_OPTION){
						hm.remove(pcInput2.getText());
						JOptionPane.showMessageDialog(null, "데이터가 삭제되었습니다");
						pcInput.setText("");
						pnInput.setText("");
						cosInput.setText("");
						pcInput2.setText("");
						
						dtm.removeRow(row);
						
						pcInput.requestFocus();

						btnMod.setEnabled(false);
						btnDel.setEnabled(false);
						btnSearch.setEnabled(true);
						mdf=true; // 수정여부
					}else{
						JOptionPane.showMessageDialog(null, "삭제가 취소되었습니다");
					}
				}
			});
			btnDel.setBounds(209, 292, 118, 23);
		}
		return btnDel;
	}
	private JButton getBtnClr() {
		if (btnClr == null) {
			btnClr = new JButton("Clear");
			btnClr.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					pcInput.setText("");
					pnInput.setText("");
					cosInput.setText("");
					pcInput2.setText("");
					for (int i=dtm.getRowCount()-1; i>-1; i--) {
						dtm.removeRow(i);
					}
					pcInput.requestFocus();
				}
			});
			btnClr.setBounds(209, 317, 118, 23);
		}
		return btnClr;
	}
	private JButton getBtnSearchAll() {
		if (btnSearchAll == null) {
			btnSearchAll = new JButton("전체조회");
			btnSearchAll.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {										
					try{
						Set<String> st = hm.keySet();	
						Iterator<String> it = st.iterator();
						if(st.isEmpty()){  // Set 에 키가 하나도 들어있지 않을때.
							JOptionPane.showMessageDialog(null, "데이터가 존재하지 않습니다.");
							return;
						}
						for (int i=dtm.getRowCount()-1; i>-1; i--) {
							dtm.removeRow(i);
						}
						while(it.hasNext()){
							pd = hm.get(it.next());													

							RowData = new Vector<String>();
							RowData.add(pd.getpCode());
							RowData.add(pd.getpName());
							RowData.add(String.valueOf(pd.getCost()));
							RowData.add(sd.format(pd.getNal()));
							dtm.addRow(RowData);
						}						
						btnMod.setEnabled(true);
						btnDel.setEnabled(true);						
					}catch(NullPointerException ex){
						JOptionPane.showMessageDialog(null, "해당 정보가 존재하지 않습니다.");
					}

				}
			});
			btnSearchAll.setBounds(221, 9, 106, 23);
		}
		return btnSearchAll;
	}	
}
